package com.adk.backend.controller;

import com.adk.backend.annotation.RequiresPermission;
import com.adk.backend.common.PageResult;
import com.adk.backend.common.Result;
import com.adk.backend.entity.LxBookingL;
import com.adk.backend.service.BookingService;
import com.adk.backend.util.LogUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * 订舱管理控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/booking")
public class BookingController {
    
    @Autowired
    private BookingService bookingService;
    
    @Autowired
    private LogUtil logUtil;
    
    /**
     * 分页查询订舱列表
     */
    @RequiresPermission("list")
    @GetMapping("/list")
    public Result<PageResult<Map<String, Object>>> getBookingList(
            @RequestParam(required = false) String planDate,
            @RequestParam(required = false) Integer txId,
            @RequestParam(required = false) Integer fromCity,
            @RequestParam(required = false) Integer toCity,
            @RequestParam(required = false) String blNo,
            @RequestParam(required = false) Integer flightStatus,
            @RequestParam(required = false) String remarks,
            @RequestParam(required = false) Integer bookingType,
            @RequestParam(required = false) String searchStartPlanDate,
            @RequestParam(required = false) String searchEndPlanDate,
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "20") Integer pageSize) {
        
        Map<String, Object> params = new HashMap<>();
        // PHP代码中 plan_date 使用 strtotime 转换为时间戳
        if (planDate != null && !planDate.isEmpty()) {
            try {
                java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd");
                java.util.Date date = sdf.parse(planDate);
                params.put("planDate", (int) (date.getTime() / 1000));
            } catch (Exception e) {
                log.warn("解析 planDate 失败: {}", planDate, e);
            }
        }
        // 处理日期范围查询
        if (searchStartPlanDate != null && !searchStartPlanDate.isEmpty() && 
            searchEndPlanDate != null && !searchEndPlanDate.isEmpty()) {
            try {
                java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd");
                java.util.Date startDate = sdf.parse(searchStartPlanDate);
                java.util.Date endDate = sdf.parse(searchEndPlanDate);
                params.put("searchStartPlanDate", (int) (startDate.getTime() / 1000));
                params.put("searchEndPlanDate", (int) (endDate.getTime() / 1000));
            } catch (Exception e) {
                log.warn("解析日期范围失败: {} - {}", searchStartPlanDate, searchEndPlanDate, e);
            }
        }
        params.put("txId", txId);
        params.put("fromCity", fromCity);
        params.put("toCity", toCity);
        params.put("blNo", blNo);
        params.put("flightStatus", flightStatus);
        params.put("remarks", remarks);
        params.put("bookingType", bookingType);
        params.put("pageNum", pageNum);
        params.put("pageSize", pageSize);
        
        PageResult<Map<String, Object>> result = bookingService.getBookingList(params);
        return Result.success(result);
    }
    
    /**
     * 根据ID查询订舱详情
     */
    @RequiresPermission("view")
    @GetMapping("/detail")
    public Result<LxBookingL> getBookingDetail(@RequestParam Long id) {
        LxBookingL booking = bookingService.getBookingById(id);
        if (booking != null) {
            return Result.success(booking);
        }
        return Result.error("订舱记录不存在");
    }
    
    /**
     * 创建订舱
     */
    @RequiresPermission("add")
    @PostMapping("/create")
    public Result<LxBookingL> createBooking(@RequestBody LxBookingL booking, HttpServletRequest request) {
        try {
            Long userId = (Long) request.getAttribute("userId");
            LxBookingL result = bookingService.createBooking(booking, userId != null ? userId.intValue() : null);
            // 记录操作日志（与PHP逻辑一致：action_logs($_SESSION['userid'], "booking_l", $tmp_id, "新建了订舱");）
            if (userId != null && result.getId() != null) {
                logUtil.logAction(userId, "booking_l", result.getId(), "新建了订舱");
            }
            return Result.success("操作成功", result);
        } catch (Exception e) {
            log.error("创建订舱失败", e);
            return Result.error("Data Error");
        }
    }
    
    /**
     * 更新订舱
     */
    @RequiresPermission("edit")
    @PostMapping("/update")
    public Result<Boolean> updateBooking(@RequestBody LxBookingL booking, HttpServletRequest request) {
        try {
            Long userId = (Long) request.getAttribute("userId");
            boolean success = bookingService.updateBooking(booking, userId != null ? userId.intValue() : null);
            if (success) {
                // 记录操作日志（与PHP逻辑一致：action_logs($_SESSION['userid'], "booking_l", $id, "更新了订舱信息");）
                if (userId != null && booking.getId() != null) {
                    logUtil.logAction(userId, "booking_l", booking.getId(), "更新了订舱信息");
                }
                return Result.success("修改成功", true);
            }
            return Result.error("Data Error");
        } catch (Exception e) {
            log.error("更新订舱失败", e);
            return Result.error("Data Error");
        }
    }
    
    /**
     * 删除订舱
     */
    @RequiresPermission("del")
    @PostMapping("/delete")
    public Result<Boolean> deleteBooking(@RequestParam Long id, HttpServletRequest request) {
        try {
            Long userId = (Long) request.getAttribute("userId");
            boolean success = bookingService.deleteBooking(id, userId != null ? userId.intValue() : null);
            if (success) {
                // 记录操作日志（与PHP逻辑一致：action_logs($_SESSION['userid'], "booking_l", $id, "删除了订舱信息");）
                if (userId != null) {
                    logUtil.logAction(userId, "booking_l", id, "删除了订舱信息");
                }
                return Result.success("删除成功", true);
            }
            return Result.error("Data Error");
        } catch (Exception e) {
            log.error("删除订舱失败", e);
            return Result.error("Data Error");
        }
    }
    
    /**
     * 查询Cargo订舱列表
     */
    @RequiresPermission("list")
    @GetMapping("/cargo/list")
    public Result<PageResult<Map<String, Object>>> getCargoBookingList(
            @RequestParam(required = false) String searchStartPlanDate,
            @RequestParam(required = false) String searchEndPlanDate,
            @RequestParam(required = false) Integer txId,
            @RequestParam(required = false) Integer fromCity,
            @RequestParam(required = false) Integer toCity,
            @RequestParam(required = false) String blNo,
            @RequestParam(required = false) Integer flightStatus,
            @RequestParam(required = false) String remarks,
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "20") Integer pageSize) {
        
        Map<String, Object> params = new HashMap<>();
        params.put("bookingType", 1); // Cargo类型
        params.put("searchStartPlanDate", searchStartPlanDate);
        params.put("searchEndPlanDate", searchEndPlanDate);
        params.put("txId", txId);
        params.put("fromCity", fromCity);
        params.put("toCity", toCity);
        params.put("blNo", blNo);
        params.put("flightStatus", flightStatus);
        params.put("remarks", remarks);
        params.put("pageNum", pageNum);
        params.put("pageSize", pageSize);
        
        PageResult<Map<String, Object>> result = bookingService.getBookingList(params);
        return Result.success(result);
    }
    
    /**
     * 查询Cou订舱列表
     */
    @RequiresPermission("list")
    @GetMapping("/cou/list")
    public Result<PageResult<Map<String, Object>>> getCouBookingList(
            @RequestParam(required = false) String searchStartPlanDate,
            @RequestParam(required = false) String searchEndPlanDate,
            @RequestParam(required = false) Integer txId,
            @RequestParam(required = false) Integer fromCity,
            @RequestParam(required = false) Integer toCity,
            @RequestParam(required = false) String blNo,
            @RequestParam(required = false) Integer flightStatus,
            @RequestParam(required = false) String remarks,
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "20") Integer pageSize) {
        
        Map<String, Object> params = new HashMap<>();
        params.put("bookingType", 2); // Cou类型
        params.put("searchStartPlanDate", searchStartPlanDate);
        params.put("searchEndPlanDate", searchEndPlanDate);
        params.put("txId", txId);
        params.put("fromCity", fromCity);
        params.put("toCity", toCity);
        params.put("blNo", blNo);
        params.put("flightStatus", flightStatus);
        params.put("remarks", remarks);
        params.put("pageNum", pageNum);
        params.put("pageSize", pageSize);
        
        PageResult<Map<String, Object>> result = bookingService.getBookingList(params);
        return Result.success(result);
    }
    
    /**
     * 获取航班信息列表
     */
    @RequiresPermission("view")
    @GetMapping("/flight/list")
    public Result<java.util.List<Map<String, Object>>> getFlightList(
            @RequestParam(required = false) Long orderId,
            @RequestParam(required = false) Long slId,
            @RequestParam(required = false) Integer type) {
        Map<String, Object> params = new HashMap<>();
        params.put("orderId", orderId);
        params.put("slId", slId);
        params.put("type", type);
        java.util.List<Map<String, Object>> flights = bookingService.getFlightList(params);
        return Result.success(flights);
    }
    
    /**
     * 添加航班信息
     */
    @RequiresPermission("add")
    @PostMapping("/flight/add")
    public Result<Boolean> addFlight(@RequestBody com.adk.backend.entity.LxBookingFlight flight) {
        try {
            boolean success = bookingService.addFlight(flight);
            if (success) {
                return Result.success("添加成功", true);
            }
            return Result.error("添加失败");
        } catch (Exception e) {
            log.error("添加航班信息失败", e);
            return Result.error("添加航班信息失败：" + e.getMessage());
        }
    }
    
    /**
     * 更新航班信息
     */
    @RequiresPermission("edit")
    @PostMapping("/flight/update")
    public Result<Boolean> updateFlight(@RequestBody com.adk.backend.entity.LxBookingFlight flight) {
        try {
            boolean success = bookingService.updateFlight(flight);
            if (success) {
                return Result.success("更新成功", true);
            }
            return Result.error("更新失败");
        } catch (Exception e) {
            log.error("更新航班信息失败", e);
            return Result.error("更新航班信息失败：" + e.getMessage());
        }
    }
    
    /**
     * 删除航班信息
     */
    @RequiresPermission("del")
    @PostMapping("/flight/delete")
    public Result<Boolean> deleteFlight(@RequestParam Long id) {
        try {
            boolean success = bookingService.deleteFlight(id);
            if (success) {
                return Result.success("删除成功", true);
            }
            return Result.error("删除失败");
        } catch (Exception e) {
            log.error("删除航班信息失败", e);
            return Result.error("删除航班信息失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取航班公司列表（type=2表示航司）
     */
    @GetMapping("/flight-companies")
    public Result<java.util.List<Map<String, Object>>> getFlightCompanies() {
        try {
            java.util.List<Map<String, Object>> companies = bookingService.getFlightCompanies();
            return Result.success(companies);
        } catch (Exception e) {
            log.error("获取航班公司列表失败", e);
            return Result.error("获取航班公司列表失败：" + e.getMessage());
        }
    }
}

